/**
 * 
 */
package pl.com.qapps.datastore.berkeley.impl;

import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;

import pl.com.qapps.datastore.TransactionCore;
import pl.com.qapps.datastore.base.AbstractTransaction;
import pl.com.qapps.datastore.base.TransactionStack;

import com.google.appengine.api.datastore.Transaction;
import com.sleepycat.je.Environment;
import com.sleepycat.je.TransactionConfig;

/**
 * @author Jakub Dykowski
 * 
 */
public class BerkeleyTransactionCore implements TransactionCore {

	private static Logger logger = Logger
			.getLogger(BerkeleyTransactionCore.class.getName());

	private final Environment env;

	protected BerkeleyTransactionCore(Environment env) {
		this.env = env;
	}

	@Override
	public Transaction beginTransaction(TransactionStack txnStack,
			ExecutorService executor) {
		TransactionConfig cfg = new TransactionConfig();
		cfg.setReadCommitted(true);
		final com.sleepycat.je.Transaction raw = env
				.beginTransaction(null, cfg);

		logger.log(Level.FINE, "Created transaction", raw.getId());
		return new AbstractTransaction(txnStack, executor) {

			@Override
			protected long getHandle() {
				return raw.getId();
			}

			@Override
			protected void doCommit() {
				logger.log(Level.FINE, "Commiting transaction...", raw.getId());
				raw.commit();
				logger.log(Level.FINE, "Tranaction commited", raw.getId());
			}

			@Override
			protected void doRollback() {
				logger.log(Level.FINER, "Aborting transaction...", raw.getId());
				raw.abort();
				logger.log(Level.FINE, "Transaction aborted", raw.getId());
			}

		};
	}

}
